﻿Imports System.Xml
Public Class frmJDBackup

    Dim setTimer As Boolean = True

#Region "이벤트"

    Private Sub backup_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Call listInit()
        Call subIconShow(Me)
        lbVersion.Text = "Ver " + gVerNo
        Dim Sql As String = "SELECT TOP 1 latestVersion FROM JDBackupInfo WHERE flag='Y' ORDER BY addDt DESC"
        gLatestVer = gSqlAFieldValue(Sql)
        Dim latestVer As String = gLatestVer

        If latestVer <> "" And latestVer <> gVerNo Then
            Dim result As Integer = MessageBox.Show("JDBackup 최신 버전(ver. " + latestVer + ")을 설치하시겠습니까?", "JDBackup", MessageBoxButtons.YesNo)
            If result = DialogResult.No Then
                Exit Sub
            ElseIf result = DialogResult.Yes Then

                'MsgBox(Mid(os.ToString, 1, 22))
                If Mid(os.ToString, 1, 22) <> "Microsoft Windows NT 5" Then
                    Try
                        Dim procInfo As New ProcessStartInfo()
                        procInfo.UseShellExecute = True
                        procInfo.FileName = (Application.StartupPath & "/updateJDBackup.exe")
                        procInfo.WorkingDirectory = ""
                        procInfo.Verb = "runas"
                        Process.Start(procInfo)
                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                Else
                    Shell(Application.StartupPath & "/updateJDBackup.exe", AppWinStyle.NormalFocus)
                End If

                Me.Dispose()
            End If
        End If
        If System.IO.File.Exists(Application.StartupPath + "/Backup.conf.xml") = True Then
            Try
                Dim config As XDocument = XDocument.Load(Application.StartupPath + "/Backup.conf.xml")

                Dim target = From t In config.Descendants("Target") Select t.Value
                Dim Interval = From t In config.Descendants("Interval") Select t.Value
                Dim setTime1 = From t In config.Descendants("SetTime1") Select t.Value
                Dim setTime2 = From t In config.Descendants("SetTime2") Select t.Value
                Dim setTime3 = From t In config.Descendants("SetTime3") Select t.Value
                Dim day1 = From t In config.Descendants("Day1") Select t.Value
                Dim day2 = From t In config.Descendants("Day2") Select t.Value
                Dim day3 = From t In config.Descendants("Day3") Select t.Value
                Dim day4 = From t In config.Descendants("Day4") Select t.Value
                Dim day5 = From t In config.Descendants("Day5") Select t.Value
                Dim day6 = From t In config.Descendants("Day6") Select t.Value
                Dim day7 = From t In config.Descendants("Day7") Select t.Value
                Dim terms = From t In config.Descendants("Terms") Select t.Value
                Dim z7 = From t In config.Descendants("Z7") Select t.Value
                Dim winStart = From t In config.Descendants("WinStart") Select t.Value
                Dim radioCheck = From t In config.Descendants("RadioCheck") Select t.Value

                txtTarget.Text = target.First
                txtInterval.Text = Interval.First
                tpSetTime1.Text = setTime1.First
                tpSetTime2.Text = setTime2.First
                tpSetTime3.Text = setTime3.First
                If day1.First = "True" Then
                    chk1.Checked = True
                End If
                If day2.First = "True" Then
                    chk2.Checked = True
                End If
                If day3.First = "True" Then
                    chk3.Checked = True
                End If
                If day4.First = "True" Then
                    chk4.Checked = True
                End If
                If day5.First = "True" Then
                    chk5.Checked = True
                End If
                If day6.First = "True" Then
                    chk6.Checked = True
                End If
                If day7.First = "True" Then
                    chk7.Checked = True
                End If
                If radioCheck.First = "1" Then
                    radio1.Checked = True
                ElseIf radioCheck.First = "2" Then
                    radio2.Checked = True
                ElseIf radioCheck.First = "3" Then
                    radio3.Checked = True
                End If

                txtTerms.Text = terms.First
                txt7Z.Text = z7.First
                If winStart.First = "True" Then
                    chkStartup.Checked = True
                End If
                'txt7Z.Text = Application.StartupPath + "/7-ZipPortable.exe"
                If txt7Z.Text <> "" Then
                    chkZip.Checked = True
                    txt7Z.Select(txt7Z.Text.Length, 0)
                End If

                Dim xmlSrc As XmlReader = XmlReader.Create(Application.StartupPath + "/Backup.conf.xml")
                Do While xmlSrc.Read
                    If xmlSrc.NodeType = XmlNodeType.Element AndAlso xmlSrc.Name = "src" Then
                        'If xmlSrc.Name = "src" Then
                        Dim folderSize As Double
                        Dim folderNm As String = xmlSrc.ReadElementString
                        folderSize = DirectorySize(New IO.DirectoryInfo(folderNm), True)
                        folderSize = CDbl(folderSize) / 1024

                        Call addListSrc(folderNm, Format(folderSize, "##,##0") + "KB")
                    Else
                        xmlSrc.Read()
                    End If
                Loop

                Call getTotalSize()
                xmlSrc.Close()
                If radio1.Checked = False And radio2.Checked = False And radio3.Checked = False Then
                    radio2.Checked = True
                End If
            Catch er As Exception
            End Try
        End If

        If ListSrc.Items.Count = 0 Or System.IO.Directory.Exists(txtTarget.Text) = False Then
            MsgBox("먼저 소스 폴더와 백업 폴더를 설정해 주세요.")
            Exit Sub
        End If

        Call BackgroundWorker2.RunWorkerAsync()
        Call subBackupDel()
        Call check7Zip()
        Dim mac As String = getMacAddr()
        Sql = "INSERT INTO JDBackupLog(mac, version) VALUES('" + mac + "','" + gVerNo + "')"
        Call gSubSaveAction(Sql, "")
        Call mkLog(">>> 시스템 시작 >>>")

    End Sub

    Private Sub backup_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        Dim result As Integer = MessageBox.Show("JDBackup을 종료 하시겠습니까?", "JDBackup", MessageBoxButtons.YesNo)
        If result = DialogResult.No Then
            e.Cancel = True
        ElseIf result = DialogResult.Yes Then
            setTimer = False
            NotifyIcon.Visible = False
            Call mkConfig()
            Call subBackupDel()
            Call mkLog("<<< 시스템 종료 <<<")
            Me.Dispose()
        End If
    End Sub

    Private Sub backup_Resize(sender As Object, e As System.EventArgs) Handles Me.Resize
        Try
            If Me.WindowState = FormWindowState.Minimized Then
                Me.Visible = False
                NotifyIcon.Visible = True
                NotifyIcon.ShowBalloonTip(1, "JDBackup-Jadesoft", "백업중입니다....", ToolTipIcon.Info)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub btnFindSrc_Click(sender As System.Object, e As System.EventArgs) Handles btnFindSrc.Click
        Dim folderSize As Long
        If FolderBrowserDlgSrc.ShowDialog() = Windows.Forms.DialogResult.OK Then
            'txtSrc.Text = FolderBrowserDlgSrc.SelectedPath
            folderSize = DirectorySize(New IO.DirectoryInfo(FolderBrowserDlgSrc.SelectedPath), True)
            folderSize = CDbl(folderSize) / 1024
            Call addListSrc(FolderBrowserDlgSrc.SelectedPath, Format(folderSize, "##,##0") + "KB")
            Call getTotalSize()
        Else
            Exit Sub
        End If
    End Sub

    Private Sub btnFindTarget_Click(sender As System.Object, e As System.EventArgs) Handles btnFindTarget.Click
        If FolderBrowserDlgTarget.ShowDialog() = Windows.Forms.DialogResult.OK Then
            txtTarget.Text = FolderBrowserDlgTarget.SelectedPath
        Else
            Exit Sub
        End If
    End Sub

    Private Sub btnBackupNow_Click(sender As System.Object, e As System.EventArgs) Handles btnBackupNow.Click

        If ListSrc.Items.Count = 0 Then
            MsgBox("소스 폴더가 지정된 곳이 없습니다.")
            btnFindSrc.Focus()
            Exit Sub
        End If
        If System.IO.Directory.Exists(txtTarget.Text) = False Then
            MsgBox("백업 폴더를 찾을 수 없습니다.")
            btnFindTarget.Focus()
            Exit Sub
        End If
        If BackgroundWorker1.IsBusy = True Then
            MsgBox("현재 지금백업실행이 진행되고 있습니다.")
        Else
            BackgroundWorker1.RunWorkerAsync()
            MsgBox("백업이 시작되었습니다")
        End If
    End Sub

    Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click

        Me.Visible = False
        NotifyIcon.Visible = True
        NotifyIcon.ShowBalloonTip(1, "JDBackup-Jadesoft", "예약 백업 작동중입니다....", ToolTipIcon.Info)
    End Sub

    Private Sub 보이기ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 보이기ToolStripMenuItem.Click
        Me.Show()
    End Sub

    Private Sub 종료ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 종료ToolStripMenuItem.Click
        Call mkConfig()
        Me.Dispose()
    End Sub

    Private Sub btnBackupPlan_Click(sender As System.Object, e As System.EventArgs) Handles btnBackupPlan.Click
        Dim msg As String = ""
        setTimer = True
        If ListSrc.Items.Count = 0 Then
            MsgBox("소스 폴더가 지정된 곳이 없습니다.")
            btnFindSrc.Focus()
            Exit Sub
        End If
        If System.IO.Directory.Exists(txtTarget.Text) = False Then
            MsgBox("백업 폴더를 찾을 수 없습니다.")
            btnFindTarget.Focus()
            Exit Sub
        End If
        If radio1.Checked = True Then
            If CInt(tpSetTime1.Text.Replace(":", "")) < CInt(Now.ToString("HHmm")) Then
                MsgBox("지속 백업 종료 시간을 현재 이후의 시간으로 설정해 주세요.")
                Exit Sub
            End If
        End If
        If BackgroundWorker2.IsBusy = False Then
            Call BackgroundWorker2.RunWorkerAsync()
        End If
        Call mkConfig()
        If radio1.Checked = True Then
            msg = "예약 백업(지속)이 설정되었습니다."
        ElseIf radio2.Checked = True Then
            msg = "예약 백업(일간)이 설정되었습니다."
        ElseIf radio3.Checked = True Then
            msg = "예약 백업(주간)이 설정되었습니다."
        End If
        MsgBox(msg)

    End Sub

    Private Sub btnBackupStop_Click(sender As System.Object, e As System.EventArgs) Handles btnBackupStop.Click
        setTimer = False
        If chkZip.Checked = True Then
            For Each prog As Process In Process.GetProcesses
                If prog.ProcessName = "7z" Then
                    prog.Kill()
                End If
            Next
        End If
        MsgBox("예약 백업이 중지 되었습니다")
    End Sub

    Private Sub NotifyIcon_DoubleClick(sender As Object, e As System.EventArgs) Handles NotifyIcon.DoubleClick

        Try
            Me.Visible = True
            Me.WindowState = FormWindowState.Normal
            NotifyIcon.Visible = False
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnOpenFolder_Click(sender As System.Object, e As System.EventArgs) Handles btnOpenFolder.Click
        If txtTarget.Text = "" Then
            MsgBox("먼저 백업 폴더를 지정해 주세요")
            btnFindTarget.Focus()
            Exit Sub
        End If
        Process.Start(txtTarget.Text)
    End Sub

    Private Sub PictureBox_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox.Click

        Process.Start("http://cafe.naver.com/inventoryman/14")
    End Sub

    Private Sub chkZip_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkZip.CheckedChanged
        If chkZip.Checked = True Then
            If txt7Z.Text = "" Then
                MsgBox("7z.exe 를 설정해주세요!" + vbCrLf + "이 기능은 7z이 설지되어 있지 않으면 사용이 불가능 합니다.")
                OpenFileDlg.ShowDialog()
                Call check7Zip()
            End If
        Else
            txt7Z.Text = ""
        End If
    End Sub
    Private Sub OpenFileDlg_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDlg.FileOk
        txt7Z.Text = OpenFileDlg.FileName
        txt7Z.Select(txt7Z.Text.Length, 0)
    End Sub

    Private Sub btnOpen7Z_Click(sender As System.Object, e As System.EventArgs) Handles btnOpen7Z.Click
        If txt7Z.Text = "" Then
            MsgBox("7z.exe 를 설정해주세요!" + vbCrLf + "이 기능은 7z이 설지되어 있지 않으면 사용이 불가능 합니다.")
        End If
        OpenFileDlg.ShowDialog()
    End Sub

    Private Sub btnExceptSrc_Click(sender As System.Object, e As System.EventArgs) Handles btnExceptSrc.Click
        For i As Integer = ListSrc.Items.Count - 1 To 0 Step -1
            If ListSrc.Items(i).Selected Then ListSrc.Items.RemoveAt(i)
        Next
        Call getTotalSize()
    End Sub

    Private Sub ListSrc_DoubleClick(sender As Object, e As System.EventArgs) Handles ListSrc.DoubleClick
        For i As Integer = ListSrc.Items.Count - 1 To 0 Step -1
            If ListSrc.Items(i).Selected Then ListSrc.Items.RemoveAt(i)
        Next
        Call getTotalSize()
    End Sub

    Private Sub chkStartup_Click(sender As Object, e As System.EventArgs) Handles chkStartup.Click
        Call startup()
    End Sub

    Private Sub btnVersion_Click(sender As System.Object, e As System.EventArgs) Handles btnVersion.Click
        frmVersion.Show()
    End Sub

    Private Sub btnLog_Click(sender As System.Object, e As System.EventArgs) Handles btnLog.Click
        frmLog.Show()
    End Sub

    Private Sub radio1_Click(sender As Object, e As System.EventArgs) Handles radio1.Click

        Call radioInit()
        setTimer = False
        Call mkLog("[BGW2] - (예약백업실행-지속) 설정되고 (예약백업실행)은 중지 되었습니다.")
        lbCom1.Enabled = True
        tpSetTime1.Enabled = True
        txtInterval.Enabled = True
    End Sub

    Private Sub radio2_Click(sender As Object, e As System.EventArgs) Handles radio2.Click

        Call radioInit()
        Call mkLog("[BGW2] - (예약백업실행-일간) 설정 되었습니다.")
        lbCom2.Enabled = True
        tpSetTime2.Enabled = True
    End Sub

    Private Sub radio3_Click(sender As Object, e As System.EventArgs) Handles radio3.Click

        Call radioInit()
        lbCom3.Enabled = True
        Call mkLog("[BGW2] - (예약백업실행-주간) 설정 되었습니다.")
        tpSetTime3.Enabled = True
        chk1.Enabled = True
        chk2.Enabled = True
        chk3.Enabled = True
        chk4.Enabled = True
        chk5.Enabled = True
        chk6.Enabled = True
        chk7.Enabled = True
    End Sub
#End Region

    Private Sub listInit()
        ListSrc.ShowItemToolTips = True
        ListSrc.View = View.Details
        ListSrc.Columns.Clear()
        ListSrc.Columns.Add("이름", 290, HorizontalAlignment.Left)
        ListSrc.Columns.Add("크기", 87, HorizontalAlignment.Right)
        ListSrc.Items.Clear()
        lbSize.Text = "0KB"
    End Sub

    Private Sub addListSrc(ByVal dir As String, ByVal dirSize As String)
        Dim addFlag As Boolean = True
        If ListSrc.Items.Count > 0 Then
            For i As Integer = ListSrc.Items.Count - 1 To 0 Step -1
                If ListSrc.Items(i).Text = dir Then
                    addFlag = False
                End If
            Next
        End If
        If addFlag = True Then
            Dim itemStr(1) As String
            Dim itemNode As ListViewItem
            itemStr(0) = dir
            itemStr(1) = dirSize
            itemNode = New ListViewItem(itemStr)
            ListSrc.Items.Add(itemNode)
        End If
    End Sub


    Private Sub startup()
        Dim regKey As Microsoft.Win32.RegistryKey
        Dim keyName As String = "JDBackup"
        Dim keyValue As String = Application.StartupPath + "/JDBackup.exe"

        regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\windows\CurrentVersion\Run", True)
        If chkStartup.Checked = True Then
            If regKey.GetValue(keyName) = Nothing Then
                regKey.SetValue(keyName, keyValue, Microsoft.Win32.RegistryValueKind.String)
                MsgBox("윈도우즈 시작시 실행이 등록 되었습니다.")
            Else
                MsgBox("이미 등록 되었습니다.")
            End If
        Else
            regKey.DeleteValue(keyName, False)
            MsgBox("윈도우즈 시작시 실행이 해제 되었습니다.")

        End If
        regKey.Close()
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Invoke(Sub()
                   Call mkConfig()
                   Call mkLog("[BGW1] - (지금백업실행) 시작")
               End Sub)
        Call subBackupDel()
        Invoke(Sub()
                   lbBakcupStatus.Text = "* 지금 백업이 진행중 입니다....!"
                   Call subPlay("start")
               End Sub)
        Dim backupDt As String = System.DateTime.Now.ToString("yyMMdd-HHmm")

        Try

            Dim sRootDir As String = ""
            Dim sDir As String = ""
            '## ListView에 등록된 자료 소스 폴더 가져오기....
            Invoke(Sub()
                       Dim srcRootDir As String = ""
                       Dim srcDir As String = ""
                       For k = 0 To ListSrc.Items.Count - 1
                           Try
                               srcDir += ListSrc.Items(k).SubItems(0).Text + "|"
                               srcRootDir += getRootFolder(ListSrc.Items(k).SubItems(0).Text) + "|"
                           Catch ex As Exception
                               MsgBox(ex.Message)
                           End Try
                       Next
                       sDir = srcDir
                       sRootDir = srcRootDir
                   End Sub)

            Dim divSRoot As String() = sRootDir.Split(New Char() {"|"c})
            Dim divS As String() = sDir.Split(New Char() {"|"c})

            If chkZip.Checked = True Then
                Try
                    Dim srcs As String = """" + sDir.Replace("|", "\"" """) + """"
                    srcs = srcs.Replace(" """"", "")
                    Dim pi As ProcessStartInfo

                    pi = New ProcessStartInfo(txt7Z.Text)
                    pi.Arguments = " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs
                    pi.UseShellExecute = True
                    pi.WindowStyle = ProcessWindowStyle.Hidden

                    Call mkLog("[BGW1] -   " + txt7Z.Text + " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs)
                    Dim prcss As Process = Process.Start(pi)
                    prcss.WaitForExit()
                Catch ex As Exception
                    Call mkLog("[BGW1] - Error : (지금백업실행) - 7z백업 에러")
                    MsgBox(ex.Message)
                End Try
            Else
                '## 단순 복사 하기
                For p = 0 To divS.Count - 1
                    If IO.Directory.Exists(divS(p)) = True Then
                        My.Computer.FileSystem.CopyDirectory(divS(p), txtTarget.Text + "/" + backupDt + "/" + divSRoot(p), True)
                        Call mkLog("[BGW1] -   " + divS(p) + " --> " + txtTarget.Text + "/" + backupDt + "/" + divSRoot(p))
                    End If
                Next

            End If

            Call mkLog("[BGW1] - (지금백업실행) 종료")
        Catch ex As Exception

            Call mkLog("[BGW1] - Error : (지금백업실행) 에러발생")
            MsgBox(ex.Message + vbCrLf + "다음의 사항을 확인해 보세요!" + vbCrLf + " 1. 소스 폴더가 정확한지 확인해 주세요." + vbCrLf + " 2. 백업 폴더가 정확한지 확인해 주세요." + vbCrLf + " 3. 백업 폴더가 위치한 하드디스크의 저장공간을 확인해 주세요.")
        End Try
        Invoke(Sub()
                   'If setTimer = False Then
                   '    lbBakcupStatus.Text = "* 예약 백업이 미설정 되어 있습니다.."
                   '    Call subPlay("stop")
                   'Else
                   '    lbBakcupStatus.Text = "* 예약 백업이 설정되었습니다."
                   '    Call subPlay("start")
                   'End If

                   'Call mkLog("[BGW1] - " + lbBakcupStatus.Text)
                   Me.Visible = True
                   NotifyIcon.Visible = False
               End Sub)

    End Sub


    Private Sub BackgroundWorker2_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
        If setTimer = True Then
            Invoke(Sub()
                       lbBakcupStatus.Text = "* 예약 백업이 설정되었습니다.."
                       Call mkLog("[BGW2] - (예약백업실행) 시작")
                       Call subPlay("start")
                   End Sub)
        Else
            Invoke(Sub()
                       lbBakcupStatus.Text = "* 예약 백업이 미설정 되어 있습니다.."
                       Call subPlay("stop")
                   End Sub)
        End If
        While setTimer

            Dim sRootDir As String = ""
            Dim sDir As String = ""
            '## ListView에 등록된 자료 소스 폴더 가져오기....
            Invoke(Sub()
                       Dim srcRootDir As String = ""
                       Dim srcDir As String = ""
                       For k = 0 To ListSrc.Items.Count - 1
                           Try
                               srcDir += ListSrc.Items(k).SubItems(0).Text + "|"
                               srcRootDir += getRootFolder(ListSrc.Items(k).SubItems(0).Text) + "|"
                           Catch ex As Exception
                               MsgBox(ex.Message)
                           End Try
                       Next
                       sDir = srcDir
                       sRootDir = srcRootDir
                   End Sub)

            Dim divSRoot As String() = sRootDir.Split(New Char() {"|"c})
            Dim divS As String() = sDir.Split(New Char() {"|"c})


            If radio1.Checked = True Then '## 지속백업
                Call subBackupDel()
                Dim actTm As String = DateAdd(DateInterval.Minute, CInt(txtInterval.Text), Now).ToString("HH:mm")
                Call mkLog("[BGW2] - * 예약 백업(지속)이 설정되었습니다.")
                While setTimer = True
                    If CInt(tpSetTime1.Text.Replace(":", "")) <= CInt(Now.ToString("HHmm")) Then
                        setTimer = False
                    End If
                    Dim backupDt As String = System.DateTime.Now.ToString("yyMMdd-HHmm")
                    Try
                        If actTm = Now.ToString("HH:mm") Then

                            Call mkLog("[BGW2] - (예약백업실행-지속)  수행 시작")
                            actTm = DateAdd(DateInterval.Minute, CInt(txtInterval.Text), Now).ToString("HH:mm")
                            Invoke(Sub()
                                       lbBakcupStatus.Text = "* 예약 백업(지속)이 진행중 입니다.....!"
                                       Call subPlay("start")
                                       lbBackupTitle.Text = "백업시작"
                                   End Sub)
                            If chkZip.Checked = True Then
                                Try
                                    Dim srcs As String = """" + sDir.Replace("|", "\"" """) + """"
                                    srcs = srcs.Replace(" """"", "")
                                    Dim pi As ProcessStartInfo

                                    pi = New ProcessStartInfo(txt7Z.Text)
                                    pi.Arguments = " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs
                                    pi.UseShellExecute = True
                                    pi.WindowStyle = ProcessWindowStyle.Hidden

                                    Call mkLog("[BGW2] -   지속 : " + txt7Z.Text + " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs)

                                    Dim prcss As Process = Process.Start(pi)
                                    prcss.WaitForExit()
                                Catch ex As Exception
                                    Call mkLog("[BGW2] - Error : (예약백업실행-지속) - 7z백업 에러")
                                    MsgBox(ex.Message)
                                End Try
                            Else
                                '## 단순 복사 하기
                                For p = 0 To divS.Count - 1
                                    If IO.Directory.Exists(divS(p)) = True Then
                                        My.Computer.FileSystem.CopyDirectory(divS(p), txtTarget.Text + "/" + backupDt + "/" + divSRoot(p), True)
                                        Call mkLog("[BGW2] -   지속 : " + divS(p) + " --> " + txtTarget.Text + "/" + backupDt + "/" + divSRoot(p))
                                    End If
                                Next

                            End If
                            Call mkLog("[BGW2] - (예약백업실행-지속) 종료")
                            System.Threading.Thread.Sleep(60000) '1분 sleep
                        Else
                            System.Threading.Thread.Sleep(1000) '1분 sleep
                        End If
                        Invoke(Sub()
                                   Call subPlay("start")
                                   lbBackupTitle.Text = "현재시간"
                                   lbCurTm.Text = Now.ToString("HH:mm:ss / yyyy.MM.dd")
                               End Sub)
                    Catch ex As Exception

                        Call mkLog("[BGW2] - Error : (예약백업실행-지속) 에러발생")
                        MsgBox(ex.Message + vbCrLf + "다음의 사항을 확인해 보세요!" + vbCrLf + " 1. 소스 폴더가 정확한지 확인해 주세요." + vbCrLf + " 2. 백업 폴더가 정확한지 확인해 주세요." + vbCrLf + " 3. 백업 폴더가 위치한 하드디스크의 저장공간을 확인해 주세요.")
                    End Try
                End While

            ElseIf radio2.Checked = True Then '## 일간백업
                If tpSetTime2.Text = Now.ToString("HH:mm") Then
                    Call mkLog("[BGW2] - (예약백업실행-일간)  수행 시작")

                    If setTimer = True Then
                        Call subBackupDel()
                        Invoke(Sub()
                                   lbBakcupStatus.Text = "* 예약 백업(일간)이 진행중 입니다.....!"
                                   Call subPlay("start")
                                   lbBackupTitle.Text = "백업시작"
                               End Sub)
                        Dim backupDt As String = System.DateTime.Now.ToString("yyMMdd-HHmm")
                        Try

                            If chkZip.Checked = True Then
                                Try
                                    Dim srcs As String = """" + sDir.Replace("|", "\"" """) + """"
                                    srcs = srcs.Replace(" """"", "")
                                    Dim pi As ProcessStartInfo

                                    pi = New ProcessStartInfo(txt7Z.Text)
                                    pi.Arguments = " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs
                                    pi.UseShellExecute = True
                                    pi.WindowStyle = ProcessWindowStyle.Hidden
                                    Call mkLog("[BGW2] -   일간 : " + txt7Z.Text + " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs)

                                    Dim prcss As Process = Process.Start(pi)
                                    prcss.WaitForExit()
                                Catch ex As Exception
                                    Call mkLog("[BGW2] - Error : (예약백업실행-일간) - 7z백업 에러")
                                    MsgBox(ex.Message)
                                End Try
                            Else
                                '## 단순 복사 하기
                                For p = 0 To divS.Count - 1
                                    If IO.Directory.Exists(divS(p)) = True Then
                                        My.Computer.FileSystem.CopyDirectory(divS(p), txtTarget.Text + "/" + backupDt + "/" + divSRoot(p), True)
                                        Call mkLog("[BGW2] -   일간 : " + divS(p) + " --> " + txtTarget.Text + "/" + backupDt + "/" + divSRoot(p))
                                    End If
                                Next

                            End If
                            Call mkLog("[BGW2] - (예약백업실행-일간) 종료")
                            Threading.Thread.Sleep(60000)
                        Catch ex As Exception

                            Call mkLog("[BGW2] - Error : (예약백업실행-일간) 에러발생")
                            MsgBox(ex.Message + vbCrLf + "다음의 사항을 확인해 보세요!" + vbCrLf + " 1. 소스 폴더가 정확한지 확인해 주세요." + vbCrLf + " 2. 백업 폴더가 정확한지 확인해 주세요." + vbCrLf + " 3. 백업 폴더가 위치한 하드디스크의 저장공간을 확인해 주세요.")
                        End Try

                    End If
                End If
                Threading.Thread.Sleep(1000)
                Invoke(Sub()
                           lbBakcupStatus.Text = "* 예약 백업(일간)이 설정되었습니다."
                           Call subPlay("start")
                           lbBackupTitle.Text = "현재시간"
                           lbCurTm.Text = Now.ToString("HH:mm:ss / yyyy.MM.dd")
                       End Sub)

            ElseIf radio3.Checked = True Then '## 주간백업
                If tpSetTime3.Text = Now.ToString("HH:mm") Then
                    Call checkPlanDay(Weekday(Now))
                    If setTimer = True And gWeekFlag = True Then
                        Call subBackupDel()
                        Call mkLog("[BGW2] - (예약백업실행-주간)  수행 시작")
                        Invoke(Sub()
                                   lbBakcupStatus.Text = "* 예약 백업(주간)이 진행중 입니다.....!"
                                   Call subPlay("start")
                                   lbBackupTitle.Text = "백업시작"
                               End Sub)
                        Dim backupDt As String = System.DateTime.Now.ToString("yyMMdd-HHmm")
                        Try

                            If chkZip.Checked = True Then
                                Try
                                    Dim srcs As String = """" + sDir.Replace("|", "\"" """) + """"
                                    srcs = srcs.Replace(" """"", "")
                                    Dim pi As ProcessStartInfo

                                    pi = New ProcessStartInfo(txt7Z.Text)
                                    pi.Arguments = " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs
                                    pi.UseShellExecute = True
                                    pi.WindowStyle = ProcessWindowStyle.Hidden
                                    Call mkLog("[BGW2] -   주간 : " + txt7Z.Text + " a -tzip """ + txtTarget.Text + "/" + backupDt + ".7z"" " + srcs)

                                    Dim prcss As Process = Process.Start(pi)
                                    prcss.WaitForExit()
                                Catch ex As Exception
                                    Call mkLog("[BGW2] - Error : (예약백업실행-주간) - 7z백업 에러")
                                    MsgBox(ex.Message)
                                End Try
                            Else
                                '## 단순 복사 하기
                                For p = 0 To divS.Count - 1
                                    If IO.Directory.Exists(divS(p)) = True Then
                                        My.Computer.FileSystem.CopyDirectory(divS(p), txtTarget.Text + "/" + backupDt + "/" + divSRoot(p), True)
                                        Call mkLog("[BGW2] -   주간 : " + divS(p) + " --> " + txtTarget.Text + "/" + backupDt + "/" + divSRoot(p))
                                    End If
                                Next

                            End If
                            Call mkLog("[BGW2] - (예약백업실행-주간) 종료")
                            Threading.Thread.Sleep(60000)
                        Catch ex As Exception
                            Call mkLog("[BGW2] - Error : (예약백업실행-주간) 에러발생")
                            MsgBox(ex.Message + vbCrLf + "다음의 사항을 확인해 보세요!" + vbCrLf + " 1. 소스 폴더가 정확한지 확인해 주세요." + vbCrLf + " 2. 백업 폴더가 정확한지 확인해 주세요." + vbCrLf + " 3. 백업 폴더가 위치한 하드디스크의 저장공간을 확인해 주세요.")
                        End Try

                    End If
                End If
                Invoke(Sub()
                           lbBakcupStatus.Text = "* 예약 백업(주간)이 설정되었습니다."
                           Call subPlay("start")
                           lbBackupTitle.Text = "현재시간"
                           lbCurTm.Text = Now.ToString("HH:mm:ss / yyyy.MM.dd")
                       End Sub)
                Threading.Thread.Sleep(1000)
            End If
        End While
        If setTimer = False Then
            Invoke(Sub()
                       lbBakcupStatus.Text = "* 예약 백업이 미설정 되어 있습니다.."
                       Call mkLog("[BGW2] - (예약백업실행) 종료.")
                       Call subPlay("stop")
                   End Sub)
        End If

    End Sub

    Private Sub getTotalSize()
        Dim tmpSize As String = ""
        Dim s As Double = 0
        For k = 0 To ListSrc.Items.Count - 1
            Try
                tmpSize = ListSrc.Items(k).SubItems(1).Text.Replace("KB", "")
                tmpSize = CDbl(tmpSize.Replace(",", ""))
                s += tmpSize

            Catch msg As Exception
                MsgBox(msg.Message)
            End Try
        Next
        If s > 1024 * 1024 * 1024 Then
            s = CDbl(s) / CDbl(1024 * 1024 * 1024)
            lbSize.Text = Format(s, "##,###.#0") + "TB"
        ElseIf s > 1024 * 1024 Then
            s = CDbl(s) / CDbl(1024 * 1024)
            lbSize.Text = Format(s, "##,###.#0") + "GB"
        ElseIf s > 1024 Then
            s = CDbl(s) / CDbl(1024)
            lbSize.Text = Format(s, "##,###.#0") + "MB"
        Else
            lbSize.Text = Format(s, "##,##0") + "KB"
        End If

    End Sub

    Private Sub mkConfig()
        Dim writer As New System.Xml.XmlTextWriter(Application.StartupPath + "/Backup.conf.xml", System.Text.Encoding.UTF8)
        Dim target, terms, setTime1, setTime2, setTime3, interval As String
        Dim winStart As String = "False"
        Dim day1, day2, day3, day4, day5, day6, day7 As String
        Dim radioChkPosit As Integer = 2

        Dim src As New List(Of String)
        Try
            writer.WriteStartDocument(True)
            writer.Formatting = System.Xml.Formatting.Indented
            writer.Indentation = 2
            writer.WriteStartElement("Config")

            For k = 0 To ListSrc.Items.Count - 1
                Try
                    src.Add(ListSrc.Items(k).SubItems(0).Text)
                Catch msg As Exception
                    MsgBox(msg.Message)
                End Try
            Next
            target = txtTarget.Text
            terms = txtTerms.Text
            setTime1 = tpSetTime1.Text
            setTime2 = tpSetTime2.Text
            setTime3 = tpSetTime3.Text
            interval = txtInterval.Text
            If chkStartup.Checked = True Then
                winStart = "True"
            End If
            day1 = "False"
            day2 = "False"
            day3 = "False"
            day4 = "False"
            day5 = "False"
            day6 = "False"
            day7 = "False"
            If chk1.Checked = True Then
                day1 = "True"
            End If
            If chk2.Checked = True Then
                day2 = "True"
            End If
            If chk3.Checked = True Then
                day3 = "True"
            End If
            If chk4.Checked = True Then
                day4 = "True"
            End If
            If chk5.Checked = True Then
                day5 = "True"
            End If
            If chk6.Checked = True Then
                day6 = "True"
            End If
            If chk7.Checked = True Then
                day7 = "True"
            End If
            If radio1.Checked = True Then
                radioChkPosit = 1
            ElseIf radio3.Checked = True Then
                radioChkPosit = 3
            Else
                radioChkPosit = 2
            End If
            writer.WriteStartElement("BackupInfo")
            writer.WriteStartElement("Source")
            For s = 0 To src.Count - 1
                writer.WriteStartElement("src")
                writer.WriteString(src(s))
                writer.WriteEndElement()
            Next
            writer.WriteEndElement()
            createNodeSingle("Target", target, writer)
            createNodeSingle("Interval", interval, writer)
            createNodeSingle("SetTime1", setTime1, writer)
            createNodeSingle("SetTime2", setTime2, writer)
            createNodeSingle("SetTime3", setTime3, writer)
            createNodeSingle("Day1", day1, writer)
            createNodeSingle("Day2", day2, writer)
            createNodeSingle("Day3", day3, writer)
            createNodeSingle("Day4", day4, writer)
            createNodeSingle("Day5", day5, writer)
            createNodeSingle("Day6", day6, writer)
            createNodeSingle("Day7", day7, writer)
            createNodeSingle("Terms", terms, writer)
            createNodeSingle("Z7", txt7Z.Text, writer)
            createNodeSingle("WinStart", winStart, writer)
            createNodeSingle("RadioCheck", radioChkPosit, writer)
            writer.WriteEndDocument()
            writer.Close()
        Catch k As Exception
            MsgBox("일시적 오류 : " + k.Message)
        End Try
    End Sub

    Private Sub createNodeSingle(ByVal str As String, ByVal val As String, ByVal writer As System.Xml.XmlTextWriter)
        writer.WriteStartElement(str)
        writer.WriteString(val)
        writer.WriteEndElement()
    End Sub

    '## 보관기간이 지난 백업 지우기
    Private Sub subBackupDel()
        If txtTarget.Text <> "" And txtTerms.Text <> "" Then
            Dim di As New IO.DirectoryInfo(txtTarget.Text)
            Dim drs As IO.DirectoryInfo() = di.GetDirectories()
            Dim drf As IO.FileInfo() = di.GetFiles()
            Dim delBackupTerms As Integer = -1 * CInt(txtTerms.Text)

            '## gBackupTerms 일 지난 백업 파일 자동 삭제
            Dim stdDt As String = DateAdd("d", delBackupTerms, DateTime.Today)
            stdDt = Mid(stdDt.Replace("-", ""), 3, 8)
            For Each dr As IO.DirectoryInfo In drs
                If Mid(dr.Name, 1, 6) < stdDt Then
                    System.IO.Directory.Delete(txtTarget.Text + "/" + dr.Name, True)
                End If
            Next
            For Each dr As IO.FileInfo In drf
                If Mid(dr.Name, 1, 6) < stdDt Then
                    System.IO.File.Delete(txtTarget.Text + "/" + dr.Name)
                End If
            Next
        End If
        '## 로그파일 삭제 - 30일 이전 로그 자동 삭제
        Dim logDi As New IO.DirectoryInfo(Application.StartupPath + "/logs")
        Dim logDrf As IO.FileInfo() = logDi.GetFiles()
        Dim logStdDt As String = DateAdd("d", -30, DateTime.Today)
        logStdDt = Mid(logStdDt.Replace("-", ""), 1, 8)

        For Each logDr As IO.FileInfo In logDrf
            'MsgBox(Mid(logDr.Name, 5, 8))
            If Mid(logDr.Name, 5, 8) < logStdDt Then
                System.IO.File.Delete(Application.StartupPath + "/logs/" + logDr.Name)
            End If
        Next

    End Sub

    Private Sub subIconShow(ByVal obj As Object)

        If Mid(os.ToString, 1, 22) <> "Microsoft Windows NT 5" Then
            obj.ShowIcon = True
            obj.Icon = My.Resources.JD
        End If
    End Sub

    Private Function DirectorySize(ByVal dInfo As IO.DirectoryInfo, ByVal includeSubDir As Boolean) As Double
        Dim totalSize As Long = dInfo.EnumerateFiles().Sum(Function(file) file.Length)
        If includeSubDir Then
            totalSize += dInfo.EnumerateDirectories().Sum(Function(dir) DirectorySize(dir, True))
        End If
        Return totalSize
    End Function

    Private Function getRootFolder(ByVal dir As String) As String
        Dim root As String
        Dim divDir As String() = dir.Split(New Char() {"\"c})
        Dim p As Integer = divDir.Count - 1
        root = divDir(p)
        Return root

    End Function
    '## 7z 설치여부에 따라 7z 사용여부 결정
    Private Sub check7Zip()
        If txt7Z.Text = "" Then
            chkZip.Enabled = False
        Else
            If System.IO.File.Exists(txt7Z.Text) = False Then
                chkZip.Enabled = False
            End If
        End If
    End Sub

    Private Sub radioInit()
        lbCom1.Enabled = False
        lbCom2.Enabled = False
        lbCom3.Enabled = False
        tpSetTime1.Enabled = False
        tpSetTime2.Enabled = False
        tpSetTime3.Enabled = False
        txtInterval.Enabled = False
        chk1.Enabled = False
        chk2.Enabled = False
        chk3.Enabled = False
        chk4.Enabled = False
        chk5.Enabled = False
        chk6.Enabled = False
        chk7.Enabled = False
        setTimer = True
    End Sub

    Private Sub checkPlanDay(ByVal dayNo As Integer)
        If chk1.Checked = True Then
            If dayNo = 1 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
        If chk2.Checked = True Then
            If dayNo = 2 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
        If chk3.Checked = True Then
            If dayNo = 3 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
        If chk4.Checked = True Then
            If dayNo = 4 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
        If chk5.Checked = True Then
            If dayNo = 5 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
        If chk6.Checked = True Then
            If dayNo = 6 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
        If chk7.Checked = True Then
            If dayNo = 7 Then
                gWeekFlag = True
            Else
                gWeekFlag = False
            End If
        End If
    End Sub

    Private Sub subPlay(ByVal flag As String)
        If flag = "start" Then
            lbStart.Enabled = True
            lbStop.Enabled = False
        Else
            lbStart.Enabled = False
            lbStop.Enabled = True
        End If
    End Sub

    '## link를 만드는 함수
    Public Sub create_shortcut()
        Dim wsh As Object = CreateObject("WScript.Shell")

        wsh = CreateObject("WScript.Shell")
        Dim MyShortcut, DesktopPath

        ' Read desktop path using WshSpecialFolders object

        DesktopPath = wsh.SpecialFolders("Desktop")

        ' Create a shortcut object on the desktop

        MyShortcut = wsh.CreateShortcut(DesktopPath & "\test.lnk")

        ' Set shortcut object properties and save it

        MyShortcut.TargetPath = wsh.ExpandEnvironmentStrings(Application.StartupPath + "\JDBackup.exe")

        MyShortcut.WorkingDirectory = wsh.ExpandEnvironmentStrings(Application.StartupPath + "\")

        MyShortcut.WindowStyle = 4

        'Use this next line to assign a icon other then the default icon for the exe

        MyShortcut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,44"

        'Save the shortcut

        MyShortcut.Save()

    End Sub

    Private Sub mkLog(ByVal logStr As String)
        Dim logFile As String = Application.StartupPath + "/logs/" + "Log_" + Now.ToString("yyyyMMdd") + ".log"
        logStr = "[" + Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + logStr

        Dim sw As System.IO.StreamWriter
        If System.IO.Directory.Exists(Application.StartupPath + "/logs") = False Then
            System.IO.Directory.CreateDirectory(Application.StartupPath + "/logs")
        End If
        If System.IO.File.Exists(logFile) = False Then
            sw = System.IO.File.CreateText(logFile)
            sw.WriteLine(logStr)
            sw.Flush()
            sw.Close()
        Else
            sw = System.IO.File.AppendText(logFile)
            sw.WriteLine(logStr)
            sw.Flush()
            sw.Close()
        End If
    End Sub

End Class
